package com.welink.cmp.statemachine.actions;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.welink.base.statemachine.Action;
import com.welink.cmp.dao.common.OperationLogService;
import com.welink.cmp.dao.metadata.FirewallDaoService;
import com.welink.cmp.dao.metadata.HostDaoService;
import com.welink.cmp.dao.metadata.RouterDaoService;
import com.welink.cmp.dao.metadata.SwitchDaoService;
import com.welink.cmp.dao.metadata.dataobject.FirewallDO;
import com.welink.cmp.dao.metadata.dataobject.HostDO;
import com.welink.cmp.dao.metadata.dataobject.RouterDO;
import com.welink.cmp.dao.metadata.dataobject.SwitchDO;
import com.welink.cmp.domain.metadata.enums.ResourceTypeEnum;
import com.welink.cmp.statemachine.context.CommonCtx;
import com.welink.cmp.statemachine.context.HostCtx;
import com.welink.cmp.statemachine.machine.CommonEvent;
import com.welink.cmp.statemachine.machine.CommonState;
import com.welink.cmp.statemachine.machine.HostEvent;
import com.welink.cmp.statemachine.machine.HostState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author yanwei li create  2024-06-11 14:46
 */
@Service
@Slf4j
public class HostActions {

    @Resource
    private OperationLogService logService;
    @Resource
    private HostDaoService hostDaoService;

    @Transactional(rollbackFor = Exception.class)
    public Action<HostState, HostEvent, HostCtx> doAction() {
        return (from, to, event, ctx)->{
            final int beforeStateCode = from.getCode();
            final int afterStateCode = to.getCode();
            hostAction(beforeStateCode,afterStateCode,event,ctx);
        };
    }


    public void hostAction(Integer beforeStateCode,Integer afterStateCode,HostEvent event,HostCtx ctx){
        LambdaUpdateWrapper<HostDO> updateWrapper = Wrappers.lambdaUpdate(HostDO.class);
        updateWrapper.set(HostDO::getStatus,afterStateCode);
        if (ctx.getLaunchedTime() != null){
            updateWrapper.set(HostDO::getLaunchedTime,ctx.getLaunchedTime());
        }
        updateWrapper.set(HostDO::getUpdateBy,ctx.getOperator());
        updateWrapper.eq(HostDO::getId,ctx.getId());
        updateWrapper.eq(HostDO::getStatus,beforeStateCode);
        final boolean update = hostDaoService.update(updateWrapper);
        if (update){
            // send some event
            // 异步处理一些事
        }
        logService.saveOperationLog(ResourceTypeEnum.HOST.getType(), ctx.getId(), event.getDescription(),"admin","操作结果："+update);
        log.info("状态机修改主机信息【防火墙 ID {}，修改后状态 {} ，修改结果{}】",ctx.getId(),afterStateCode,update);
    }


}
